<?php

!defined('IN') && exit('Access denied');

ini_set('display_errors', 1);
error_reporting(E_ALL &~ E_NOTICE);

set_time_limit(0);

header("Content-type:text/html; charset=utf-8");
header("Expires: Mon, 26 Jul 1970 05:00:00 GMT"); 
header("Last-Modified: ".gmdate('D, d M Y H:i:s')." GMT");
header("Cache-control: no-cache, must-revalidate");
header("Pragma: no-cache");


unset($GLOBALS);

$_ENV = array();

define('__PATH__',dirname(__FILE__));
define('CACHE_PATH',__PATH__.'/source/cache/');
define('ATTACH_PATH',__PATH__.'/attach/');
define('IN_SYSTEM',1);
define('POST',strtolower($_SERVER['REQUEST_METHOD']) === 'post');
define('AJAX',(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') OR $_GET['inajax'] == '1');
define('REFER',$_SERVER['HTTP_REFERER']);
define('AUTH_KEY','this is custom auth secret key'.$_SERVER['HTTP_USER_AGENT']);

date_default_timezone_set('PRC');

$_ENV['time'] = time();

session_name('TG_JSID');
session_start();

/**
 * 加载全局配置文件
 */
$config = array();
@include __PATH__.'/source/config.global.php';
$_ENV['config'] =  $config;

/**
 * 加载所需文件
 */
require __PATH__.'/source/function/function_core.php';
define('FORMHASH',formhash());

/**
 * 配置系统
 */
spl_autoload_register('import');

/**
 * 连接数据库
 */
$_ENV['db'] = new class_db($_ENV['config']['db']['host'],$_ENV['config']['db']['user'],$_ENV['config']['db']['pass'],$_ENV['config']['db']['name']);

/**
 * 加载系统设置
 */
$config = array();
if (class_cache::has('config')) {
    $config = class_cache::read('config');
} else {
    $rowset = $_ENV['db']->fetchAll("SELECT * FROM `setting`");
    foreach ((array)$rowset as $row) {
        $config[$row['k']] = $row['v'];
    }

    class_cache::write('config',$config);
}
$_ENV['config'] = array_merge($_ENV['config'],$config);
unset($config);

/**
 * 初始化商品分类
 */
$product_class = array();
if (class_cache::has('product_class')) {
    $product_class = class_cache::read('product_class');
} else {
    $rowset = $_ENV['db']->fetchAll("SELECT * FROM `product_class` order by sort");
    class_cache::write('product_class',$rowset);
    $product_class =& $rowset;
}


/**
 * 初始化文章分类
 */
$article_class = array();
if (class_cache::has('article_class')) {
    $article_class = class_cache::read('article_class');
} else {
    $rowset2 = $_ENV['db']->fetchAll("SELECT * FROM article_class order by sort");
    class_cache::write('article_class',$rowset);
    $article_calss =& $rowset2;
}

/**
 * 请求过滤
 */
if(!get_magic_quotes_gpc()) {
    $_GET = caddslashes($_GET);
    $_POST = caddslashes($_POST);
    $_REQUEST = array_merge($_GET,$_POST);
    $_COOKIE = caddslashes($_COOKIE);
}

function showMainFrontPage($tpl) {
    $view = class_view::getInstance();
    $view->page = $tpl;
    $view->render('front/layout');
}

// 初始化模板引擎
$template = class_view::getInstance();

// 初始化用户登陆状态
$_G = array();

$user = cauthcode(cgetcookie('fu'),'DECODE');
if ($user) {
    $user = json_decode($user,1);
    $_G['cid']       = $user['customer_id'];    //客户ID
	$_G['uid']       = $user['leader_id'];      //客户下领导ID
    $_G['username']  = $user['username'];
    $_G['state']     = $user['state'];
    unset($user);
}

$template->_G = $_G;

//顶部导航
$sname = basename($_SERVER['SCRIPT_NAME']);
foreach (explode("\n",$_ENV['config']['snavi']) as $item) {
    list($name,$tag,$url) = explode(':',$item);
    if (basename($url) == $sname) $current[$name] = ' class="current"';
}

// 统计购物车商品数量
$_ENV['cart_num'] = 0;
if ($_G['uid']) {
    $_ENV['cart_num'] = $_ENV['db']->fetchCol("SELECT count(1) FROM cart WHERE `uid` = '{$_G['uid']}'");
}

// 最新动态
// 最新动态文章列表id
$news = $_ENV['db']->fetchAll("SELECT * FROM article WHERE cid!='13' ");
$template->news = $news;

/*[数字化校园]*/
$template->company = htmlspecialchars_decode(cmsEntity::GetCompanyContent());

/*[一卡通]*/
$template->service = htmlspecialchars_decode(cmsEntity::GetServiceContent());

/*[数字能源监管系统]*/
$template->case = cmsEntity::GetCaseContent();

/*[金融IC卡推广方案]*/
$template->success = cmsEntity::GetSuccessContent();

/*[行业方案]*/
$template->hangye = cmsEntity::GetHangyeContent();

/*[行业范围]*/
$template->type = str_replace("\r",null,htmlspecialchars(cmsEntity::GetTypeContent()));

/*[图片]*/
//$template->picture = explode("\n",str_replace("\r",null,htmlspecialchars(sourceEntity::GetPictureContent())));//sourceEntity::GetPictureContent();
$template->picture = $_ENV['db']->fetchAll("SELECT * FROM lunbo ORDER BY lid DESC");

/*动态*/
$template->gonggaos = sourceEntity::GetGongGaoList();


/*公告*/
$template->dongtai= cmsEntity::GetdongtaiList();


// 定义函数
# 需要用户登陆
function needLogin() {
    global $_G;
    if (!$_G['uid']) {
        if (AJAX) {
            outputJson(-403,'请登陆后操作');
        } else {
            exit('<script>alert("请登陆后操作");window.location.href="user.php?act=login"</script>');
        }
    }
}
# 显示商品图片
function showProductImage($data,$size='small') {
	if($data['filepath'])
	{
		return './attach/'.$data['filepath'].'/'.$data['hash'].'_'.$size.'.'.$data['ext'];
	}else{
		return './image/no_picture.gif';
	}
}
# 输出JSON并结束
function outputJson($state,$message,$extra='') {
    echo json_encode(array('state'=>$state,'message'=>$message,'extra'=>$extra));
    exit;
}
# 拼凑SQL
function buildSql($array) {
    $sql = '';

    foreach ($array as $key=>$val) $sql .= "`{$key}`='{$val}',";

    return 'SET '.substr($sql,0,-1);
}